<?php

namespace IDock\Insurance\AICS\Response;

use IDock\Http\Response;
use IDock\IDock\IDockEnums;
use IDock\Insurance\AICS\AICSEnums;
use IDock\Printer\NonCar\NonCarInquiryPrinter;
use IDock\Printer\NonCar\NonCarInquirySinglePrinter;
use IDock\Printer\Premium\PremiumBIPrinter;
use IDock\Printer\Premium\PremiumCIPrinter;
use IDock\Printer\Premium\PremiumCoveragePrinter;
use IDock\Printer\Premium\PremiumFactorPrinter;
use IDock\Printer\Premium\PremiumInquiryPrinter;
use IDock\Printer\Premium\PremiumTaxPrinter;
use IDock\Printer\SpecialClausesPrinter;
use IDock\Visitor\NonCar\NonCarProductVisitor;

class PremiumInquiryResponse extends AllAICSResponse
{
    public function resolve(): Response
    {
        $body = $this->getBody();
        $body = str_replace('&lt;', '<', $body);
        $body = str_replace('&gt;', '>', $body);
        $body = str_replace("'", '"', $body);
        $start = strpos($body, '<response>');
        $end = strpos($body, '</response>');
        $body = substr($body, $start + 10, $end - $start - 10);
        if ($body) {
            if (substr(trim($body), '0', 1) == '<') {
                libxml_disable_entity_loader(false);

                $body = simplexml_load_string($body);
                $body = $this->objectToArray($body);
                $errorCode = $body['Head']['errorCode'] ?? '';
                $message = $body['Head']['errorMessage'] ?? '未知错误';
            } else {
                $message = $body;
                $errorCode = '';
            }
            $this->setBody($body);
            if ($errorCode !== '000000' && strpos($message, '重复投保') === false) {
                $this->setError($message);
                return $this;
            }
        }
        return $this;
    }

    public function printerInit(): Response
    {
        $premiumInquiryPrinter = new PremiumInquiryPrinter();
        $data = $this->getBody();
        $error = $data['Head']['errorMessage'] ?? '未知错误';
        $biError = $data['TfiWarnList']['tfiWarnData'][1]['warnMessage'] ?? '';

        $this->getCIRepeatData($premiumInquiryPrinter, $error);
        $this->getBIRepeatData($premiumInquiryPrinter, $biError);

        if ($premiumInquiryPrinter->repeatInsuredFlg) {
            $premiumInquiryPrinter->success = false;
            $this->printer = $premiumInquiryPrinter;
            return $this;
        }
        if (($data['Head']['errorCode'] ?? '') != '000000') {
            $this->setError($error);
            return $this;
        }
        //存一下税务信息
        $premiumInquiryPrinter->argc['cTaxType'] = $data['taxATion']['cTaxType'] ?? [];
        $premiumInquiryPrinter->argc['clntMark'] = $data['taxATion']['clntMark'] ?? [];
        $premiumInquiryPrinter->argc['clntAddress'] = $data['taxATion']['clntAddress'] ?? [];
        $premiumInquiryPrinter->argc['mobile'] = $data['taxATion']['mobile'] ?? [];
        $premiumInquiryPrinter->argc['bankName'] = $data['taxATion']['bankName'] ?? [];
        $premiumInquiryPrinter->argc['acctNo'] = $data['taxATion']['acctNo'] ?? [];
        $premiumInquiryPrinter->success = true;
        $jqData = $data['CvrgListJQ']['cvrgJQ'] ?? [];
        //交强险
        $premiumInquiryPrinter->inquiryNo = '';//总询价单号
        $premiumInquiryPrinter->ciInquiryNo = '';
        $premiumInquiryPrinter->biInquiryNo = '';
        $jqRate = $data['VehicleAdjust'] ?? [];
        $ciPremiumPrinter = new PremiumCIPrinter();
        $ciPremiumPrinter->ciPremium = $jqData['coveragePremium'] ?? '0';//交强险保费
        $ciPremiumPrinter->ciStartData = $data['Base']['TInsrncBgnTmJQ'] ?? '';//交强险起保日期
        $ciPremiumPrinter->ciEndData = $data['Base']['TInsrncEndTmJQ'] ?? '';//交强险终保日期
        $ciPremiumPrinter->ciBasePremium = $jqData['befTaxPrm'] ?? '0';//交强险保费（不含增值税）
        $ciPremiumPrinter->ciDiscount = round($jqRate['recDiscount'] ?? '', 2) ?? '1';//交强折扣率
        $premiumInquiryPrinter->ciPremiumPrinter = $ciPremiumPrinter;
        //存一下车架号
        $premiumInquiryPrinter->argc['vin'] = $data['Vhl']['CFrmNo'] ?? '';
        //存下查询码
        $premiumInquiryPrinter->argc['CQryCdeSY'] = $data['Vhl']['CQryCdeSY'] ?? '';//商业险查询码
        $premiumInquiryPrinter->argc['CQryCdeJQ'] = $data['Vhl']['CQryCdeJQ'] ?? '';//交强险查询码
        $carTaxPrinter = new PremiumTaxPrinter();
        $tax = $data['Tax'] ?? [];
        $carTaxPrinter->carShipTax = $tax['sumUpTax'] ?? 0;
        $carTaxPrinter->thisYearTax = $tax['currentTax'] ?? 0;//本年应缴税
        $carTaxPrinter->overdue = $tax['lateFee'] ?? 0;
        $carTaxPrinter->payBackTax = $tax['payLastYear'] ?? 0;
        $premiumInquiryPrinter->carTaxPrinter = $carTaxPrinter;

        $biData = $data['CvrgListSY']['cvrgSY'] ?? '';
        $biPremiumPrinter = new PremiumBIPrinter();
        $biPremiumPrinter->biPremium = 0;//商业险保费
        $biPremiumPrinter->biStartData = $data['Base']['TInsrncBgnTmSY'] ?? '';//商业险起保日期
        $biPremiumPrinter->biEndData = $data['Base']['TInsrncEndTmSY'] ?? '';//商业险终保日期
//        $biPremiumPrinter->biDiscount = $biData['itemKindList']['itemKindInfo'][0]['discount'] ?? '';
        $premiumInquiryPrinter->biPremiumPrinter = $biPremiumPrinter;

        //特约
        if (!empty($data['FixspecListJQ']['fixspecDataJQ'])) foreach ($data['FixspecListJQ']['fixspecDataJQ'] as $val) {
            $engage = new SpecialClausesPrinter();
            $engage->clauseCode = $val['specNo'];
            $engage->clauseContent = $val['specContent'];
            $engage->autoFlag = $val['modify'] ?? '';
            $engage->riskType = 'TCI';//交强险
            $premiumInquiryPrinter->specialClausesAppend($engage);
        }
        if (!empty($data['FixspecListSY']['fixspecDataSY'])) foreach ($data['FixspecListSY']['fixspecDataSY'] as $val) {
            $engage = new SpecialClausesPrinter();
            $engage->clauseCode = $val['specNo'];
            $engage->clauseContent = $val['specContent'];
            $engage->autoFlag = $val['modify'] ?? '';
            $engage->riskType = 'VCI';//商业险
            $premiumInquiryPrinter->specialClausesAppend($engage);
        }

        $coverageList = $data['CvrgListSY']['cvrgSY'] ?? [];
        $biBasePremium = 0;
        $coverageList = $this->formatArray($coverageList);
        foreach ($coverageList as $row) {
            $coverage = new PremiumCoveragePrinter();
            $coverage->coverageCode = array_search($row['CCvrgNo'], AICSEnums::$coverageCode);
            $coverage->coverageName = IDockEnums::$coverageCode[$coverage->coverageCode];

            if ($coverage->coverageCode == 'C05001' or $coverage->coverageCode== 'C15001') {
                $coverage->unitAmount = $row['NPerAmt'] ?? '0';
                $coverage->quantity = $row['NLiabDaysLmt'] ?? '1';
            } else {
                $coverage->amount = $row['NPerAmt'] ?? '0';
            }

            $coverage->premium = $row['NPrm'] ?? 0;
            $coverage->basePremium = $row['NBasePrm'] ?? 0;
            if ($coverage->basePremium) {
                $coverage->discount = round($coverage->premium / $coverage->basePremium, 2);
            }
            $biBasePremium += $coverage->basePremium;
            $biPremiumPrinter->biPremium += $coverage->premium;
            $coverage->serviceTimes = $row['NLiabDaysLmt'] ?? '0';
            $premiumInquiryPrinter->coverageListAppend($coverage);
        }
        $biPremiumPrinter->biBasePremium = $biBasePremium;
        $vehicle = $data['Vhl'] ?? [];
        $CRkScore = $vehicle['cRkScore'] ?? '';
        //交商系数
        $riskRatio = $data['VehicleAdjust'] ?? [];
        $biRate = $data['PrmCoef'] ?? [];
        $premiumInquiryPrinter->ncdFactor = $data['PrmCoef']['NAgoClmRecQuick'] ?? '';
        $factorPrinter = new PremiumFactorPrinter();
        $factorPrinter->TCIFactorAppend('上一保险年度有责交通故事或有责任赔款记录浮动比例', 'DutyReparFloatingRate', $riskRatio['dutyReparFloatingRate'] ?? '');
        $factorPrinter->TCIFactorAppend('总体浮动系数', 'OverallFloatingCoefficient', $riskRatio['overallFloatingCoefficient'] ?? '');
        $factorPrinter->TCIFactorAppend('建议折扣（交强）', 'recDiscount', $riskRatio['recDiscount'] ?? '');
        $factorPrinter->TCIFactorAppend('与道路交通事故相联系的浮动比率（%）', 'roadAccidentFloatingRateValue', $riskRatio['roadAccidentFloatingRateValue'] ?? '');
        $factorPrinter->TCIFactorAppend('酒后驾驶违法行为费率浮动比例', 'drunkDrivingFloatingRate', $riskRatio['drunkDrivingFloatingRate'] ?? '');
        $factorPrinter->TCIFactorAppend('上一保险年度道路交通安全违章行为记录浮动比例', 'roadViolatFloatingRate', $riskRatio['roadViolatFloatingRate'] ?? '');

        $factorPrinter->VCIFactorAppend('交通违法系数(商业)', 'biNecompensationRate', $biRate['NPeccancyAdjustValue'] ?? '');
        $factorPrinter->VCIFactorAppend('自主核保系数(商业)', 'NAutonomyAdjust', $biRate['NAutonomyAdjust'] ?? '');
        $factorPrinter->VCIFactorAppend('自主渠道系数(商业)', 'NChannelAdjust', $biRate['NChannelAdjust'] ?? '');
        $factorPrinter->VCIFactorAppend('成本折扣(商业)', 'NResvNum3', $biRate['NResvNum3'] ?? '');
        $factorPrinter->VCIFactorAppend('建议折扣(商业)', 'NResvNum5', $biRate['NResvNum5'] ?? '');
        $factorPrinter->VCIFactorAppend('总体折扣(商业)', 'NTotDisc', $biRate['NTotDisc'] ?? '');
        $factorPrinter->VCIFactorAppend('附加费用率', 'NAdditionalCostRate', $biRate['NAdditionalCostRate'] ?? '');
        $factorPrinter->VCIFactorAppend('绝对免赔额费率折扣系数（商业）', 'NabsoDedu', $biRate['NabsoDedu'] ?? '');
        $factorPrinter->VCIFactorAppend('核保折扣（商业）', 'NUwdisc', $biRate['NUwdisc'] ?? '');
        $factorPrinter->VCIFactorAppend('投保组合（商业）', 'CInsuranceGroup', $biRate['CInsuranceGroup'] ?? '');
        $factorPrinter->VCIFactorAppend('连续承保年数（商业）', 'NInsureYears', $biRate['NInsureYears'] ?? '');
        $factorPrinter->VCIFactorAppend('连续承保期间出险次数 （商业）', 'NClaimTimes', $biRate['NClaimTimes'] ?? '');
        $factorPrinter->VCIFactorAppend('无赔优系数级别 （商业）', 'CClaimAdjustLevel', $biRate['CClaimAdjustLevel'] ?? '');

        $loyalty = ['0' => '新', '1' => '续', '2' => '转'];
        $factorPrinter->ComFactorAppend('自主定价系数', 'selfPricingCoef', $biRate['NPricingAdjustValue'] ?? '');

        $factorPrinter->ComFactorAppend('商业手续费比例', 'NCommRateSY', $data['Base']['NCommRateSY'] ?? '');
        $factorPrinter->ComFactorAppend('交强手续费比例', 'NCommRateJQ', $data['Base']['NCommRateJQ'] ?? '');

        $factorPrinter->ComFactorAppend('光博业务分类', 'CWeRisk', $data['Base']['CWeRisk'] ?? '');
        $factorPrinter->ComFactorAppend('交强险忠诚度', 'CIRenewalType', $loyalty[$data['Base']['cBusType '] ?? ''] ?? '');
        $factorPrinter->ComFactorAppend('商业险忠诚度', 'BIRenewalType', $loyalty[$data['Base']['cBusType '] ?? ''] ?? '');
//        $factorPrinter->ComFactorAppend('睿控评分','CRkScore',$CRkScore);
        $factorPrinter->ComFactorAppend('车慧达评分', 'cCheHuiScore', $vehicle['cCheHuiScore'] ?? '');

        //非车信息
        $noCarList = $data['itemKindslist']['itemKinds'] ?? [];
        if (!empty($noCarList)) {
            $proposal = $data['proposal'] ?? [];
            $nonCarInquiryPrinter = new NonCarInquiryPrinter();
            $noCarList = $this->formatArray($noCarList);
            foreach ($noCarList as $val) {
                /*** @var $item NonCarProductVisitor */
                $single = new NonCarInquirySinglePrinter();
                $single->premium = $val['premium'] ?? '0';
                $single->planCode = $val['clauseCode'] ?? '';
                $single->productCode = '';
                $single->statusCode = 'success';
                $single->insuredNum = $proposal['nInsuranceQuantity'] ?? '';
                $nonCarInquiryPrinter->noCarInquirySingleAppend($single);
            }
            $nonCarInquiryPrinter->totalPremium = $proposal['premium'] ?? '';
            $premiumInquiryPrinter->nonCarInquiryPrinter = $nonCarInquiryPrinter;
        }

        $premiumInquiryPrinter->premiumFactorPrinter = $factorPrinter;
        $this->printer = $premiumInquiryPrinter;
        return $this;
    }

    public function formatArray(array $arr): array
    {
        if (empty($arr)) return $arr;
        if (!isset($arr[0])) {
            $tmp = $arr;
            unset($arr);
            $arr[] = $tmp;
        }
        return $arr;
    }

    public function buildCoverage($isEnergy, array $orgList)
    {
        $orgList = array_combine(array_column($orgList, 'coverageCode'), $orgList);

        foreach ($this->printer->coverageList as $coverage) {
            /*** @var $coverage PremiumCoveragePrinter */

            if ($isEnergy) {
                $coverage->coverageCode = 'C1' . substr($coverage->coverageCode, 2, 4);
                $coverage->coverageName = IDockEnums::$coverageCode[$coverage->coverageCode];
            }

            if (!$coverage->amount) {
                $coverage->amount = $orgList[$coverage->coverageCode]->amount ?? '';
            }

            $coverage->quantity = $orgList[$coverage->coverageCode]->quantity ?? '';
            $coverage->unitAmount = $orgList[$coverage->coverageCode]->unitAmount ?? '';
            //服务次数回写
            $coverage->serviceTimes = $orgList[$coverage->coverageCode]->serviceTimes ?? '';
        }
    }

    /**
     * 重复投保
     * @param PremiumInquiryPrinter $premiumInquiryPrinter
     * @param $ciError
     * @return void
     */
    public function getCIRepeatData(PremiumInquiryPrinter $premiumInquiryPrinter, $ciError)
    {
        if (!$ciError) {
            return;
        }

        if (preg_match('/终保日期 ([\d\s:-]+)/', $ciError, $matches)) {
            if ($matches[1] ?? '') {
                $ciStartData = date('Y-m-d H:i:s', strtotime($matches[1]));
                $premiumInquiryPrinter->repeatInsurePrinter['ciStartData'] = $ciStartData;
                $premiumInquiryPrinter->repeatInsuredFlg = true;

                $premiumInquiryPrinter->repeatMessage = $ciError;
            }
        }
    }

    private function getBIRepeatData(PremiumInquiryPrinter $premiumInquiryPrinter, $biError)
    {
        if (!$biError) {
            return;
        }

        if (preg_match('/终保日期：([\d\s:-]+)/', $biError, $matches)) {
            if ($matches[1] ?? '') {
                $biStartData = date('Y-m-d H:i:s', strtotime($matches[1]));
                $premiumInquiryPrinter->repeatInsurePrinter['biStartData'] = $biStartData;
                $premiumInquiryPrinter->repeatInsuredFlg = true;

                $premiumInquiryPrinter->repeatMessage = $biError;
            }
        }
    }
}
